package com.wthink.hzgj.util

import android.content.Context
import android.view.KeyEvent
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.wthink.hzgj.R
import com.wthink.hzgj.state.StateFragment

@Suppress("UNCHECKED_CAST")
fun <F : Fragment> AppCompatActivity.getFragment(fragmentClass: Class<F>): F? {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment

    navHostFragment.childFragmentManager.fragments.forEach {
        if (fragmentClass.isAssignableFrom(it.javaClass)) {
            return it as F
        }
    }

    return null
}

fun Fragment.onBackKey(listener: () -> Boolean) {
    view?.isFocusableInTouchMode = true
    view?.requestFocus()
    view?.setOnKeyListener { v, keyCode, event ->
        if (keyCode != KeyEvent.KEYCODE_BACK) {
            return@setOnKeyListener false
        }

        listener()
    }
}

fun Fragment.closeDefaultAnimator(recyclerView: RecyclerView) {
    recyclerView.itemAnimator?.apply {
        setAddDuration(0)
        setChangeDuration(0)
        setMoveDuration(0)
        setRemoveDuration(0)
        if (this is SimpleItemAnimator) {
            supportsChangeAnimations = false
        }
    }
}

fun Fragment.openDefaultAnimator(recyclerView: RecyclerView) {
    recyclerView.itemAnimator?.apply {
        setAddDuration(120)
        setChangeDuration(250)
        setMoveDuration(250)
        setRemoveDuration(120)
        if (this is SimpleItemAnimator) {
            supportsChangeAnimations = true
        }
    }
}

fun toast(context: Context, msg: String, time: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(context, msg, time).show()
}